#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import logging
import re
import json
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')

FILE_NAME = "Test.json"
LANGUAGE = "json"
ENCODING = 'utf-8'

ERROR_TYPE_APPFREEZE = "XTS.CHECK.APPFREEEZE.01"
ERROR_DESC_APPFREEZE = "XTS工程Test.json中不允许引入规避命令"
ERROR_TYPE_ABILITYMS = "XTS.CHECK.ABILITYMS.01"
ERROR_DESC_ABILITYMS = "XTS工程Test.json中不允许引入屏蔽弹窗命令"
ERROR_TYPE_SETENFORCE = "XTS.CHECK.SETENFORCE.01"
ERROR_DESC_SETENFORCE = "XTS工程Test.json中不允许开启selinux"


def check_method(func):
    def wrapper(cls):
        file_entities = utils_data.get_file()
        if not file_entities:
            logger.error("未获取到文件信息，无法进行检查")
            return
        return func(cls, file_entities)

    return classmethod(wrapper)


class JsonConfigChecker:
    @staticmethod
    def check_file_for_pattern(file_entities, target_pattern, error_type, error_desc):
        has_error = False
        for entity in file_entities:
            if entity.file_name == FILE_NAME:
                file_path = entity.full_path
                try:
                    with open(file_path, 'r', encoding=ENCODING) as file:
                        content_lines = file.readlines()
                        for line_idx, line in enumerate(content_lines):
                            match = re.search(target_pattern, line)
                            if match:
                                error_info = ErrorInfoBuilder() \
                                    .set_buggy_file_path(entity.file_path) \
                                    .set_defect_type(error_type) \
                                    .set_description(error_desc) \
                                    .set_main_buggy_line(line_idx + 1) \
                                    .set_main_buggy_code(line.strip()) \
                                    .set_language(LANGUAGE) \
                                    .build()

                                utils_data.write_error_to_json_file(error_info)
                                logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                                has_error = True
                except Exception as e:
                    logger.error(f"读取文件 {file_path} 时发生错误: {e}")
        return has_error

    @check_method
    def check_setenforce_zero(cls, file_entities):
        target_pattern = r'setenforce\s+0'
        has_error = cls.check_file_for_pattern(file_entities, target_pattern, ERROR_TYPE_SETENFORCE,
                                               ERROR_DESC_SETENFORCE)
        if has_error:
            logger.info("Test.json setenforce 0 命令检查完成，错误信息已写入xts_result.json")
        else:
            logger.info("Test.json setenforce 0 命令检查通过")

    @check_method
    def check_appfreeze_filter(cls, file_entities):
        target_pattern = r'param set hiviewdfx.appfreeze.filter_bundle_name [^\"]+'
        has_error = cls.check_file_for_pattern(file_entities, target_pattern, ERROR_TYPE_APPFREEZE,
                                               ERROR_DESC_APPFREEZE)
        if has_error:
            logger.info("Test.json规避命令检查完成，错误信息已写入xts_result.json")
        else:
            logger.info("Test.json规避命令检查通过")

    @check_method
    def check_abilityms_false(cls, file_entities):
        target_pattern = r'param set persist.sys.abilityms.support.ecologicalrulemgrservice false'
        has_error = cls.check_file_for_pattern(file_entities, target_pattern, ERROR_TYPE_ABILITYMS,
                                               ERROR_DESC_ABILITYMS)
        if has_error:
            logger.info("Test.json弹窗屏蔽命令检查完成，错误信息已写入xts_result.json")
        else:
            logger.info("Test.json弹窗屏蔽命令检查通过")